import cn.hutool.core.util.RandomUtil;
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import lombok.Getter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * description  nacos 权重发布配置
 *
 * @author TigerLin
 * @version 1.0
 * create 2024/06/24  23:41
 */
@Configuration
@ConditionalOnNacosDiscoveryEnabled
// 在执行 nacos 注册前执行本操作
@AutoConfigureBefore({NacosDiscoveryClientConfiguration.class})
@ConditionalOnProperty(prefix = WoodsElectWeightConfiguration.PREFIX, name = "enabled",havingValue = "true", matchIfMissing = true)

public class WoodsElectWeightConfiguration {
    public static final String PREFIX = "spring.cloud.nacos.discovery.watch";
    public static final String ELECT_WEIGHT_NAME = "elect_weight";
    /**
     * 选举权重
     */
    @Getter
    Long electWeight = System.currentTimeMillis() << 41 + RandomUtil.randomInt();
    /**
     * 选举状态
     */
    Boolean electStatus = false;

    /**
     * 判断是否是主节点
     * @return  true:主节点  false:从节点
     */
    public Boolean isMaster(){
        return electStatus;
    }

    public void setElectStatus(Boolean electStatus) {
        this.electStatus = electStatus;
    }

    public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties){
        // 从 nacos 获取本系统的元数据
        Map<String,String> metadata = nacosDiscoveryProperties.getMetadata();
        // 未获取到元数据，创建元数据
        if(null == metadata){
            metadata = new HashMap<>();
            nacosDiscoveryProperties.setMetadata(metadata);
        }
        //
        metadata.put(ELECT_WEIGHT_NAME,electWeight.toString());
        return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties);
    }

}
